//
//  MLSNewFeatureController.swift
//  MLSMircoBlog
//
//  Created by 袁航 on 15/7/31.
//  Copyright © 2015年 yuanhang. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let imageCount = 4
class MLSNewFeatureController: UICollectionViewController {
    
    
    // 布局属性
    private let layout = MLSFlowlayout()
    
    //MARK: - 重写init方法,方便外界快速创建
    init() {
        super.init(collectionViewLayout: layout)
    }
    
    //MARK: - SB和代码混合开发的时候需要考虑
    required init?(coder aDecoder: NSCoder) {
        super.init(collectionViewLayout: layout)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Register cell classes
        self.collectionView!.registerClass(MLSCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
    }
    
    // MARK: UICollectionViewDataSource
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return imageCount
    }
    
    // 返回cell
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MLSCollectionViewCell
        
        // Configure the cell
        cell.imageItem = indexPath.item
        
        return cell
    }
    
    // 当现实最后一个cell的时候,开始动画
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        // 获取当前显示的cell的indexPath,并判断是否是最后一个cell
        if let currendPath = collectionView.indexPathsForVisibleItems().last where currendPath.item == imageCount - 1 {
            
            // 获取最后一个cell(能够进来,就表示是最后一个cell)
            let lastCell = collectionView.cellForItemAtIndexPath(currendPath) as! MLSCollectionViewCell
            
            // 开始动画
            lastCell.startButtonAnimation()
        }
        
        
        
    }
    
}

//MARK:- 自定义cell
class MLSCollectionViewCell: UICollectionViewCell {
    
    // 图像索引 外界赋值属性,设置图片,同一个文件允许访问
    private var imageItem: Int = 0 {
        didSet{
            backImage.image = UIImage(named: "new_feature_\(imageItem + 1)")
            // 如果不是最后一页,隐藏按钮
            button.hidden = (imageItem != imageCount - 1)
            // 每次显示cell的时候,都让button的transform的scale为0
            button.transform = CGAffineTransformMakeScale(0, 0)
        }
    }
    
    
    // 重写init方法,注册cell时调用init(frame)方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUpUI()
    }
    
    //MARK:- 立即体验按钮点击方法
    func supButtonClick() {
        // 发送通知,要求更换控制器
        NSNotificationCenter.defaultCenter().postNotificationName(MLSChangeRootviewControllerNotifaction, object: self, userInfo: [MLSChangeRootVCNotiUserInfoKey : MLSWelcomeController()])
    }
    //MARK:- 按钮动画
    func startButtonAnimation() {
        // 开始动画的时候,禁用按钮
        button.userInteractionEnabled = false
        // block动画(button开始的时候,transform就是0)
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10.0, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            self.button.transform = CGAffineTransformIdentity
            }) { (finshed) -> Void in
                if finshed {
                    // 动画完成后,让按钮可用
                    self.button.userInteractionEnabled = true
                }
        }
    }
    
    // 布局控件
    private func setUpUI() {
        backImage.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(backImage)
        button.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(button)
        
        // 使用第三方框架布局
        // 背景图片填充
        backImage.ff_Fill(contentView)
        // 按钮布局
        button.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160))
    }
    
    ///  懒加载控件
    // 背景图片
    lazy var backImage = UIImageView()
    
    // 立即体验按钮
    lazy var button: UIButton = {
        let button = UIButton()
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.setTitle("立即体验", forState: UIControlState.Normal)
        // 添加button的点击方法
        button.addTarget(self, action: "supButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        // 初始的时候,transform为0
        button.transform = CGAffineTransformMakeScale(0, 0)
        return button
        }()
}

//MARK:- 自定义流水布局
class MLSFlowlayout: UICollectionViewFlowLayout {
    ///  当准备好cell的数量之后,会调用一次.而且此时的collectionView的尺寸已定
    /// 如果还没有设置 layout，获取数量之后，准备cell之前，会被调用一次
    /*:
    / The collection view calls -prepareLayout once at its first layout as the first message to the layout instance.
    当第一次接收到布局信息的时候,collectionView 会调用一次prepareLayout方法
    
    // The collection view calls -prepareLayout again after layout is invalidated and before requerying the layout information.
    当布局失效,或者在查询布局信息之前,collectionView会再次调用一次该方法
    
    // Subclasses should always call super if they override.
    子控件重写该方法,不用super都总会先调用父类的该方法
    */
    override func prepareLayout() {
        // 设置flowLayout的基本信息
        itemSize = collectionView!.frame.size
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        // 设置collectionView的基本属性
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
}